using Android.App;
using Android.Content;
using Android.OS;
using Android.Views;
using Android.Widget;
using AF.Activities;
using AF.Data;
using AF.Models;
using Android.Content.PM;

namespace AF
{
    [Activity(Label = "@string/app_name", MainLauncher = true, Theme = "@android:style/Theme.Material.Light.NoActionBar")]
    public class MainActivity : Activity
    {
        private DatabaseHelper? dbHelper;
        private TextView? textTotalIncome;
        private TextView? textTotalExpense;
        private Button? btnAddExpense;
        private Button? btnAddIncome;
        private Button? btnProjects;
        private Button? btnStatistics;
        private Button? btnExport;
        private TextView? textViewAllProjects;
        private ListView? listViewProjects;
        private TextView? textEmptyProjects;
        private ListView? listViewTransactions;
        private TextView? textEmptyState;

        private List<Project> projects = new List<Project>();
        private List<Transaction> transactions = new List<Transaction>();

        protected override void OnCreate(Bundle? savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            dbHelper = new DatabaseHelper(this);

            InitializeViews();
            SetupEventHandlers();
            
            // 请求存储权限（Android 6.0+）
            if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                if (CheckSelfPermission(Android.Manifest.Permission.WriteExternalStorage) != Permission.Granted)
                {
                    RequestPermissions(new string[] 
                    { 
                        Android.Manifest.Permission.WriteExternalStorage,
                        Android.Manifest.Permission.ReadExternalStorage
                    }, 1);
                }
            }
        }

        protected override void OnResume()
        {
            base.OnResume();
            LoadData();
        }

        private void InitializeViews()
        {
            textTotalIncome = FindViewById<TextView>(Resource.Id.textTotalIncome);
            textTotalExpense = FindViewById<TextView>(Resource.Id.textTotalExpense);
            btnAddExpense = FindViewById<Button>(Resource.Id.btnAddExpense);
            btnAddIncome = FindViewById<Button>(Resource.Id.btnAddIncome);
            btnProjects = FindViewById<Button>(Resource.Id.btnProjects);
            btnStatistics = FindViewById<Button>(Resource.Id.btnStatistics);
            btnExport = FindViewById<Button>(Resource.Id.btnExport);
            textViewAllProjects = FindViewById<TextView>(Resource.Id.textViewAllProjects);
            listViewProjects = FindViewById<ListView>(Resource.Id.listViewProjects);
            textEmptyProjects = FindViewById<TextView>(Resource.Id.textEmptyProjects);
            listViewTransactions = FindViewById<ListView>(Resource.Id.listViewTransactions);
            textEmptyState = FindViewById<TextView>(Resource.Id.textEmptyState);
        }

        private void SetupEventHandlers()
        {
            if (btnAddExpense != null)
            {
                btnAddExpense.Click += (s, e) =>
                {
                    var intent = new Intent(this, typeof(AddTransactionActivity));
                    intent.PutExtra("type", (int)TransactionType.Expense);
                    StartActivity(intent);
                };
            }

            if (btnAddIncome != null)
            {
                btnAddIncome.Click += (s, e) =>
                {
                    var intent = new Intent(this, typeof(AddTransactionActivity));
                    intent.PutExtra("type", (int)TransactionType.Income);
                    StartActivity(intent);
                };
            }

            if (btnProjects != null)
            {
                btnProjects.Click += (s, e) =>
                {
                    var intent = new Intent(this, typeof(ProjectsActivity));
                    StartActivity(intent);
                };
            }

            if (btnStatistics != null)
            {
                btnStatistics.Click += (s, e) =>
                {
                    var intent = new Intent(this, typeof(StatisticsActivity));
                    StartActivity(intent);
                };
            }

            if (btnExport != null)
            {
                btnExport.Click += (s, e) => ExportData();
            }

            if (textViewAllProjects != null)
            {
                textViewAllProjects.Click += (s, e) =>
                {
                    var intent = new Intent(this, typeof(ProjectsActivity));
                    StartActivity(intent);
                };
            }

            if (listViewProjects != null)
            {
                listViewProjects.ItemClick += (s, e) =>
                {
                    var project = projects[e.Position];
                    var intent = new Intent(this, typeof(ProjectDetailActivity));
                    intent.PutExtra("project_id", project.Id);
                    intent.PutExtra("project_name", project.Name);
                    StartActivity(intent);
                };
            }

            if (listViewTransactions != null)
            {
                listViewTransactions.ItemClick += (s, e) =>
                {
                    var transaction = transactions[e.Position];
                    ShowTransactionOptions(transaction);
                };
            }
        }

        private void LoadData()
        {
            if (dbHelper == null) return;

            // 加载本月统计数据
            var now = DateTime.Now;
            var startDate = new DateTime(now.Year, now.Month, 1);
            var endDate = startDate.AddMonths(1).AddDays(-1);

            var (totalIncome, totalExpense, balance) = dbHelper.GetStatistics(startDate, endDate);

            if (textTotalIncome != null)
                textTotalIncome.Text = $"¥{totalIncome:N2}";

            if (textTotalExpense != null)
                textTotalExpense.Text = $"¥{totalExpense:N2}";

            // 加载进行中的项目列表
            projects = dbHelper.GetAllProjects()
                .Where(p => p.Status == ProjectStatus.InProgress)
                .Take(3)  // 只显示前3个项目
                .ToList();

            if (listViewProjects != null && textEmptyProjects != null)
            {
                if (projects.Count > 0)
                {
                    listViewProjects.Visibility = ViewStates.Visible;
                    textEmptyProjects.Visibility = ViewStates.Gone;

                    var projectAdapter = new MainProjectAdapter(this, projects, dbHelper);
                    listViewProjects.Adapter = projectAdapter;
                    SetListViewHeightBasedOnChildren(listViewProjects);
                }
                else
                {
                    listViewProjects.Visibility = ViewStates.Gone;
                    textEmptyProjects.Visibility = ViewStates.Visible;
                }
            }

            // 加载交易记录列表
            transactions = dbHelper.GetAllTransactions();

            if (listViewTransactions != null && textEmptyState != null)
            {
                if (transactions.Count > 0)
                {
                    listViewTransactions.Visibility = ViewStates.Visible;
                    textEmptyState.Visibility = ViewStates.Gone;

                    var adapter = new TransactionAdapter(this, transactions);
                    listViewTransactions.Adapter = adapter;
                }
                else
                {
                    listViewTransactions.Visibility = ViewStates.Gone;
                    textEmptyState.Visibility = ViewStates.Visible;
                }
            }
        }

        private void ShowTransactionOptions(Transaction transaction)
        {
            var items = new string[] { "查看详情", "删除" };

            new AlertDialog.Builder(this)!
                .SetTitle("操作")!
                .SetItems(items, (s, e) =>
                {
                    if (e.Which == 0)
                    {
                        ShowTransactionDetails(transaction);
                    }
                    else if (e.Which == 1)
                    {
                        ConfirmDeleteTransaction(transaction);
                    }
                })!
                .Show();
        }

        private void ShowTransactionDetails(Transaction transaction)
        {
            string typeText = transaction.Type == TransactionType.Income ? "收入" : "支出";
            string message = $"类型：{typeText}\n" +
                           $"金额：¥{transaction.Amount:N2}\n" +
                           $"分类：{transaction.CategoryName}\n" +
                           $"描述：{transaction.Description}\n" +
                           $"日期：{transaction.Date:yyyy-MM-dd HH:mm}\n" +
                           $"备注：{transaction.Remark ?? "无"}";

            new AlertDialog.Builder(this)!
                .SetTitle("交易详情")!
                .SetMessage(message)!
                .SetPositiveButton("确定", (s, e) => { })!
                .Show();
        }

        private void ConfirmDeleteTransaction(Transaction transaction)
        {
            new AlertDialog.Builder(this)!
                .SetTitle("确认删除")!
                .SetMessage("确定要删除这条记录吗？")!
                .SetPositiveButton("删除", (s, e) =>
                {
                    if (dbHelper != null)
                    {
                        int result = dbHelper.DeleteTransaction(transaction.Id);
                        if (result > 0)
                        {
                            Toast.MakeText(this, "删除成功", ToastLength.Short)?.Show();
                            LoadData();
                        }
                        else
                        {
                            Toast.MakeText(this, "删除失败", ToastLength.Short)?.Show();
                        }
                    }
                })!
                .SetNegativeButton("取消", (s, e) => { })!
                .Show();
        }

        protected override void OnDestroy()
        {
            base.OnDestroy();
            dbHelper?.Close();
        }

        private void ExportData()
        {
            if (dbHelper == null) return;

            try
            {
                // 创建导出数据对象
                var exportData = new ExportData
                {
                    AppName = "易帐",
                    Version = "2.3",
                    ExportDate = DateTime.Now,
                    Categories = dbHelper.GetAllCategories(),
                    Projects = dbHelper.GetAllProjects(),
                    Transactions = dbHelper.GetAllTransactions()
                };

                // 计算统计信息
                var allTransactions = exportData.Transactions;
                exportData.Statistics = new ExportStatistics
                {
                    TotalTransactions = allTransactions.Count,
                    TotalProjects = exportData.Projects.Count,
                    TotalIncome = allTransactions.Where(t => t.Type == TransactionType.Income).Sum(t => t.Amount),
                    TotalExpense = allTransactions.Where(t => t.Type == TransactionType.Expense).Sum(t => t.Amount),
                    TotalBalance = allTransactions.Where(t => t.Type == TransactionType.Income).Sum(t => t.Amount) -
                                  allTransactions.Where(t => t.Type == TransactionType.Expense).Sum(t => t.Amount),
                    EarliestDate = allTransactions.Any() ? allTransactions.Min(t => t.Date) : null,
                    LatestDate = allTransactions.Any() ? allTransactions.Max(t => t.Date) : null
                };

                // 序列化为JSON
                string json = System.Text.Json.JsonSerializer.Serialize(exportData, new System.Text.Json.JsonSerializerOptions
                {
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });

                // 生成文件名
                string fileName = $"易帐数据_{DateTime.Now:yyyyMMdd_HHmmss}.json";
                
                // 保存到下载目录
                Java.IO.File? downloadsDir = Android.OS.Environment.GetExternalStoragePublicDirectory(
                    Android.OS.Environment.DirectoryDownloads);
                
                if (downloadsDir != null)
                {
                    Java.IO.File file = new Java.IO.File(downloadsDir, fileName);
                    
                    using (var writer = new System.IO.StreamWriter(file.AbsolutePath))
                    {
                        writer.Write(json);
                    }

                    // 通知用户
                    string message = $"数据已导出！\n\n" +
                                   $"文件名：{fileName}\n" +
                                   $"位置：下载文件夹\n\n" +
                                   $"共导出：\n" +
                                   $"· {exportData.Projects.Count} 个项目\n" +
                                   $"· {exportData.Transactions.Count} 条记录\n" +
                                   $"· {exportData.Categories.Count} 个分类";

                    new AlertDialog.Builder(this)!
                        .SetTitle("导出成功")!
                        .SetMessage(message)!
                        .SetPositiveButton("确定", (s, e) => { })!
                        .SetNeutralButton("打开文件夹", (s, e) =>
                        {
                            // 打开文件管理器到下载目录
                            var intent = new Intent(Intent.ActionView);
                            intent.SetDataAndType(Android.Net.Uri.FromFile(downloadsDir), "resource/folder");
                            intent.SetFlags(ActivityFlags.NewTask);
                            try
                            {
                                StartActivity(intent);
                            }
                            catch
                            {
                                Toast.MakeText(this, "请手动打开文件管理器查看", ToastLength.Short)?.Show();
                            }
                        })!
                        .Show();
                }
                else
                {
                    Toast.MakeText(this, "无法访问下载目录", ToastLength.Short)?.Show();
                }
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, $"导出失败：{ex.Message}", ToastLength.Long)?.Show();
            }
        }

        private void SetListViewHeightBasedOnChildren(ListView listView)
        {
            var adapter = listView.Adapter;
            if (adapter == null) return;

            int totalHeight = 0;
            for (int i = 0; i < adapter.Count; i++)
            {
                View? listItem = adapter.GetView(i, null, listView);
                if (listItem != null)
                {
                    listItem.Measure(0, 0);
                    totalHeight += listItem.MeasuredHeight;
                }
            }

            ViewGroup.LayoutParams? parameters = listView.LayoutParameters;
            if (parameters != null)
            {
                parameters.Height = totalHeight + (listView.DividerHeight * (adapter.Count - 1));
                listView.LayoutParameters = parameters;
                listView.RequestLayout();
            }
        }
    }

    // 主界面的简化项目适配器
    public class MainProjectAdapter : BaseAdapter<Project>
    {
        private readonly Activity context;
        private readonly List<Project> items;
        private readonly DatabaseHelper dbHelper;

        public MainProjectAdapter(Activity context, List<Project> items, DatabaseHelper dbHelper)
        {
            this.context = context;
            this.items = items;
            this.dbHelper = dbHelper;
        }

        public override Project this[int position] => items[position];

        public override int Count => items.Count;

        public override long GetItemId(int position) => position;

        public override View? GetView(int position, View? convertView, ViewGroup? parent)
        {
            var view = convertView ?? context.LayoutInflater.Inflate(
                Resource.Layout.list_item_project, null);

            var project = items[position];

            var textProjectName = view?.FindViewById<TextView>(Resource.Id.textProjectName);
            var textProjectStatus = view?.FindViewById<TextView>(Resource.Id.textProjectStatus);
            var textClientName = view?.FindViewById<TextView>(Resource.Id.textClientName);
            var textProjectDate = view?.FindViewById<TextView>(Resource.Id.textProjectDate);
            var textProjectIncome = view?.FindViewById<TextView>(Resource.Id.textProjectIncome);
            var textProjectExpense = view?.FindViewById<TextView>(Resource.Id.textProjectExpense);
            var textProjectBalance = view?.FindViewById<TextView>(Resource.Id.textProjectBalance);

            if (textProjectName != null)
                textProjectName.Text = project.Name;

            if (textProjectStatus != null)
            {
                textProjectStatus.Text = "进行中";
                textProjectStatus.SetBackgroundColor(Android.Graphics.Color.ParseColor("#4CAF50"));
            }

            if (textClientName != null)
            {
                if (!string.IsNullOrWhiteSpace(project.ClientName))
                {
                    textClientName.Text = $"客户：{project.ClientName}";
                    textClientName.Visibility = ViewStates.Visible;
                }
                else
                {
                    textClientName.Visibility = ViewStates.Gone;
                }
            }

            if (textProjectDate != null)
            {
                var days = (DateTime.Now - project.StartDate).Days;
                textProjectDate.Text = $"已进行 {days} 天";
            }

            // 获取项目统计
            var (income, expense, balance, count) = dbHelper.GetProjectStatistics(project.Id);

            if (textProjectIncome != null)
                textProjectIncome.Text = $"¥{income:N2}";

            if (textProjectExpense != null)
                textProjectExpense.Text = $"¥{expense:N2}";

            if (textProjectBalance != null)
                textProjectBalance.Text = $"¥{balance:N2}";

            return view;
        }
    }

    public class TransactionAdapter : BaseAdapter<Transaction>
    {
        private readonly Activity context;
        private readonly List<Transaction> items;

        public TransactionAdapter(Activity context, List<Transaction> items)
        {
            this.context = context;
            this.items = items;
        }

        public override Transaction this[int position] => items[position];

        public override int Count => items.Count;

        public override long GetItemId(int position) => position;

        public override View? GetView(int position, View? convertView, ViewGroup? parent)
        {
            var view = convertView ?? context.LayoutInflater.Inflate(
                Resource.Layout.list_item_transaction, null);

            var transaction = items[position];

            var textCategoryIcon = view?.FindViewById<TextView>(Resource.Id.textCategoryIcon);
            var textCategory = view?.FindViewById<TextView>(Resource.Id.textCategory);
            var textDescription = view?.FindViewById<TextView>(Resource.Id.textDescription);
            var textDate = view?.FindViewById<TextView>(Resource.Id.textDate);
            var textAmount = view?.FindViewById<TextView>(Resource.Id.textAmount);

            if (textCategoryIcon != null)
            {
                // 可以根据分类ID从数据库获取图标，这里简化处理
                textCategoryIcon.Text = transaction.Type == TransactionType.Income ? "💰" : "💸";
            }

            if (textCategory != null)
                textCategory.Text = transaction.CategoryName;

            if (textDescription != null)
            {
                textDescription.Text = string.IsNullOrWhiteSpace(transaction.Description)
                    ? "无描述"
                    : transaction.Description;
            }

            if (textDate != null)
                textDate.Text = transaction.Date.ToString("yyyy-MM-dd");

            if (textAmount != null)
            {
                string prefix = transaction.Type == TransactionType.Income ? "+" : "-";
                textAmount.Text = $"{prefix}¥{transaction.Amount:N2}";
                
                var color = transaction.Type == TransactionType.Income
                    ? Android.Graphics.Color.ParseColor("#4CAF50")
                    : Android.Graphics.Color.ParseColor("#F44336");
                textAmount.SetTextColor(color);
            }

            return view;
        }
    }
}
